#include "DBManager.h"
#include "Config.h"

typedef IDatabase*(*InitCallback)();
typedef void(*KillCallback)(IDatabase*);

DBInstance::DBInstance(Module* mod)
{
	moduleHandle = mod;
	dbHandle = NULL;
	if (mod)
	{
		InitCallback init = (InitCallback)mod->GetFunc("InitModule");
		if (init)
		{
			dbHandle = init();
		}
	}
}

DBInstance::~DBInstance()
{
	if (dbHandle)
	{
		KillCallback kill = (KillCallback)moduleHandle->GetFunc("DestroyModule");
		if (kill)
		{
			kill(dbHandle);
		}
	}
	if (moduleHandle)
	{
		delete moduleHandle;
	}
}

IDatabase* DBInstance::operator->()
{
	return dbHandle;
}

IDatabase* DBInstance::GetDBHandle()
{
	return dbHandle;
}

IDatabase* DBInstance::operator*()
{
	return *dbHandle;
}

IDatabase* DBInstance::GetDBReference()
{
	return *dbHandle;
}

DBManager::DBManager()
{
}

DBManager::~DBManager()
{
}

Handle<DBInstance> DBManager::NewDatabaseInstance()
{
	Handle<DBInstance> h;
	if (currentModule == "")
	{
		fprintf(stderr, "DBManager.NewDatabaseInstance: Cannot load module\n");
		return h;
	}
	Module* mod = new Module(currentModule);
	h = new DBInstance(mod);
	return h;
}

DBManager& DBManager::Instance()
{
	static DBManager _instance;
	return _instance;
}

void DBManager::Init()
{
	currentModule = conf.GetValue("database.module");
}